-- 居安思危
local juansiwei = fk.CreateSkill {
    name = "mcdh_juansiwei",
    frequency = Skill.Compulsory,
}

juansiwei:addEffect(fk.EventPhaseStart,{
    can_trigger =function(self, event, target, player, data)
        local room = player.room
        local logic = room.logic
        if player:hasSkill(self)  and target ~= player and target.phase == Player.Finish then
            if #logic:getActualDamageEvents( 1, function(e) return e.data[1].to ~= player end) ~= 0 and #logic:getActualDamageEvents(player.room, 1, function(e) return e.data[1].to == player end) == 0 then
                local ids = {}
                room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
                    for _, move in ipairs(e.data) do
                        if move.toArea == Card.DiscardPile  then
                            for _, info in ipairs(move.moveInfo) do
                                if room:getCardArea(info.cardId) == Card.DiscardPile  then
                                    table.insertIfNeed(ids, info.cardId)
                                end
                            end
                        end
                    end
                end, Player.HistoryTurn)
                if #ids > 0 then
                    self.cost_data = ids
                    return true
                end
            end
        end
    end,
    on_cost =function(self, event, target, player, data)
        local ids = self.cost_data
        if #ids == 1 then
            self.cost_data = ids[1]
            return true
        else
            local cards, _ = U.askforChooseCardsAndChoice(player, ids, {"OK"}, self.name,
                    "#juansiwei-choose", nil, 1, 1)
            self.cost_data = cards[1]
            return true
        end
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        room:obtainCard(player,self.cost_data, true, fk.ReasonPrey)
    end
})

return juansiwei